package com.blue.firecat.controller;


import com.alibaba.fastjson.JSON;
import com.blue.firecat.contants.Contants;
import com.blue.firecat.contants.Result;
import com.blue.firecat.entity.Game;
import com.blue.firecat.entity.OrderExample;
import com.blue.firecat.entity.User;
import com.blue.firecat.enums.ErrorEnum;
import com.blue.firecat.enums.OrderTypeEnum;
import com.blue.firecat.serivce.GameService;
import com.blue.firecat.serivce.OrderService;
import com.blue.firecat.serivce.TradeService;
import com.blue.firecat.serivce.UserService;
import com.blue.firecat.utils.controller.BaseController;
import com.blue.firecat.utils.verifycode.VerifyCode;
import com.blue.firecat.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * 描述
 * 时间 2017-6-21 11:10
 * 作者 肖亦鸣
 */
@Controller
@RequestMapping("user")
public class UserController extends BaseController {
    private static Logger logger = LogManager.getLogger(UserController.class.getName());
    @Autowired
    UserService userService;
    @Autowired
    GameService gameService;
    @Autowired
    TradeService tradeService;
    @Autowired
    OrderService orderService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(User user, String loginCode) {
        logger.info("loginCode:{},user:{}", loginCode, JSON.toJSONString(user));
        //todo
        if (loginCode == null || !loginCode.equalsIgnoreCase(String.valueOf(request.getSession().getAttribute("validateCode")))) {
            request.setAttribute(Contants.MESSAGE, ErrorEnum.CODE_INVALID.getValue());
//            return "login";
        }
//        user.setUserName("admin");
//        user.setPassword("admin");
        if (user == null || StringUtils.isEmpty(user.getPassword()) || StringUtils.isEmpty(user.getUserName())) {
            request.setAttribute(Contants.MESSAGE, ErrorEnum.PARAMETER_CANNOT_NULL.getValue());
            return "loginNew";
        }
        Result<User> result = userService.login(user);
        if (result.isFail()) {
            logger.info("login fail:{}", JSON.toJSONString(result));
            request.setAttribute(Contants.MESSAGE, result.getMessage());
            request.setAttribute(Contants.OBJECT, result.getData());
            return "loginNew";
        } else {
            request.getSession().setAttribute(Contants.USER_SESSION, result.getData());
        }
        logger.info("login success:{}", JSON.toJSONString(result.getData()));
        return "redirect:index";
    }

    @RequestMapping("index")
    public String index() {
        Result<List<Game>> result = gameService.selectByExample(null);
        request.setAttribute(Contants.GAMES, result.getData());
        request.setAttribute("can", Contants.ORDER_COUNT_MAP.get(OrderTypeEnum.WAITING.getValue()) == null ? 0 : Contants.ORDER_COUNT_MAP.get(OrderTypeEnum.WAITING.getValue()));
//        request.setAttribute(Contants.TRADES, Contants.TRADE_GAME_RESULT.getData());
        request.setAttribute(Contants.TRADES, Contants.TRADE_STATUS_RESULT);

        Result<Map<String, Integer>> tradeResult = tradeService.countByExample(getUserBySession());
        request.setAttribute(Contants.TRADE_COUNTS, tradeResult.getData());
        request.setAttribute("tradeNumber", Contants.getNumberByMap(tradeResult.getData()));
        return "index";
    }

    @RequestMapping(value = "/index.html")
    public String user() {
        return "loginNew";
    }

    @RequestMapping("validateCode")
    public void validateCode(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        VerifyCode vc = new VerifyCode();
        BufferedImage image = vc.getImage();
        request.getSession().setAttribute("validateCode", vc.getText());
        VerifyCode.output(image, response.getOutputStream());
        logger.info("login code:{}", vc.getText());
    }

    @RequestMapping("logout")
    public String logout() {
        request.getSession().invalidate();
        return "loginNew";
    }

    @ResponseBody
    @RequestMapping(value = "getAllBeater", produces = {"text/json;charset=UTF-8"})
    public String getAllBeater() {
        Result<List<User>> result = userService.getAllBeater();
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result.getData());
    }

    @ResponseBody
    @RequestMapping(value = "getAllCustom", produces = {"text/json;charset=UTF-8"})
    public String getAllCustom() {
        Result<List<User>> result = userService.getAllCustom();
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result.getData());
    }

    /**
     * 返回添加用户的信息接受页面
     *
     * @param user
     * @return
     */
    @RequestMapping("memberAdd")
    public String memberAdd(User user) {
        return "member-add";
    }

    /**
     * 接受输入的用户信息，插入数据库
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "addUser", method = RequestMethod.POST)
    public String addUser(User user) {
        logger.info("user:{}", JSON.toJSONString(user));
        request.setAttribute(Contants.OBJECT, user);
        if (user.getType() == null) {
            request.setAttribute(Contants.MESSAGE, ErrorEnum.USER_TYPE_NOT_EXIST.getValue());
            return "member-add";
        }
        Result<User> result = userService.insertSelective(user, getUserBySession());
        request.setAttribute(Contants.MESSAGE, result.getMessage());
        logger.info("result:{}", JSON.toJSONString(result));
        return "member-add";
    }

    @RequestMapping("memberList")
    public String memberList() {
        Result<List<User>> result = userService.selectByExample(getUserBySession());
        request.setAttribute(Contants.USERS, result.getData());
        logger.info("result:{}", JSON.toJSONString(result));
        return "member-list";
    }

    @RequestMapping("memberShow")
    public String memberShow(Long userId) {
        Result<User> result = userService.selectByPrimaryKey(userId, getUserBySession());
        request.setAttribute(Contants.OBJECT, result.getData());
        logger.info("result:{}", JSON.toJSONString(result));
        return "member-show";
    }

    @RequestMapping("productList")
    public String productList() {
        return "product-list";
    }

    @RequestMapping("welcome")
    public String welcome() {
        //交易统计
        Result<Map<String, Integer>> tradeResult = tradeService.countByExample(getUserBySession());
        request.setAttribute(Contants.TRADE_COUNTS, tradeResult.getData());
        request.setAttribute("tradeNumber", Contants.getNumberByMap(tradeResult.getData()));
        request.setAttribute("tradeAllCount", tradeService.count());
        //金额统计
        Result<Object> resultMoney = tradeService.countMoneyByExample(getUserBySession());
        request.setAttribute(Contants.MONEY, resultMoney.getData());
        //订单统计
        Result<Map<String, Integer>> orderResult = orderService.countByExample(getUserBySession());
        request.setAttribute(Contants.ORDER_COUNTS, orderResult.getData());
        request.setAttribute("orderNumber", Contants.getNumberByMap(orderResult.getData()));
        request.setAttribute("orderAllCount", orderService.count());
        //可接单统计
        request.setAttribute("can", Contants.ORDER_COUNT_MAP.get(OrderTypeEnum.WAITING.getValue()) == null ? 0 : Contants.ORDER_COUNT_MAP.get(OrderTypeEnum.WAITING.getValue()));
        //游戏缓存
        this.cacheHelp();
        logger.info("tradeResult:{},orderResult:{}", JSON.toJSONString(tradeResult), JSON.toJSONString(orderResult));
        return "welcome";
    }

    @RequestMapping("userInfo")
    public String userInfo() {
        User user = getUserBySession();
        Result<User> result = userService.selectByPrimaryKey(user.getId(), getUserBySession());
        request.setAttribute(Contants.OBJECT, result.getData());
        logger.info("result:{}", JSON.toJSONString(result));
        return "user-info";
    }

    /**
     * 修改用户个人信息
     *
     * @param user
     * @return "user-info";
     */
    @RequestMapping(value = "modifyInfo", method = RequestMethod.POST)
    public String modifyInfo(User user) {
        logger.info("user:{}", JSON.toJSONString(user));
        Result<User> result = userService.updateByPrimaryKeySelective(user);
        request.setAttribute(Contants.OBJECT, result.getData());
        request.setAttribute(Contants.MESSAGE, result.getMessage());
        logger.info("result:{}", JSON.toJSONString(result));
        return "user-info";
    }

    /**
     * 返回将要被修改用户的个人信息
     *
     * @param id
     * @return "user-modify";
     */
    @RequestMapping("userModify")
    public String userModify(Long id) {
        logger.info("id:{}", id);
        Result<User> result = userService.selectByPrimaryKey(id, getUserBySession());
        request.setAttribute(Contants.OBJECT, result.getData());
        logger.info("result:{}", JSON.toJSONString(result));
        return "user-modify";
    }

    /**
     * 将传入的用户信息更新到数据库
     *
     * @param user
     * @return "user-modify";
     */
    @RequestMapping(value = "userUpdate", method = RequestMethod.POST)
    public String userUpdate(User user) {
        logger.info("user:{}", JSON.toJSONString(user));
        Result<User> result = userService.updateByPrimaryKeySelective(user);
        request.setAttribute(Contants.OBJECT, result.getData());
        request.setAttribute(Contants.MESSAGE, result.getMessage());
        logger.info("result:{}", JSON.toJSONString(result));
        return "user-modify";
    }

    @RequestMapping(value = "userStatusModify", method = RequestMethod.POST)
    public String userStatusModify() {
        return "user-info";
    }

    @RequestMapping(value = "userDelete", method = RequestMethod.POST)
    public String userDelete() {
        return "member-list";
    }

    /**
     * 启用或停用用户的状态
     *
     * @param userId
     * @return "user-modify";
     */
    @ResponseBody
    @RequestMapping(value = "stopOrStartUser", produces = {"text/json;charset=UTF-8"})
    public String stopOrStartUser(Integer status, Long userId) {
        logger.info("userId:{},status:{}", userId, status);
        Result<User> result = userService.stopUser(getUserBySession(), userId, status);
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    @ResponseBody
    @RequestMapping(value = "deleteUser", produces = {"text/json;charset=UTF-8"})
    public String deleteUser(Long userId) {
        logger.info("userId:{}", userId);
        Result<User> result = userService.deleteByPrimaryKey(getUserBySession(), userId);
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    @RequestMapping("modifyPassword")
    public String modifyPassword() {
        return "modify-password";
    }

    @RequestMapping(value = "updatePassword", method = RequestMethod.POST)
    public String updatePassword(UserVo userVo) {
        logger.info("userVo:{}", JSON.toJSONString(userVo));
        Result<User> userResult = userService.updatePassword(userVo);
        request.setAttribute(Contants.MESSAGE, userResult.getMessage());
        return "modify-password";
    }

    @RequestMapping("register.html")
    public String toRegister() {
        return "registerNew";
    }

    @RequestMapping("register")
    public String register(User user) {
        logger.info("user:{}", JSON.toJSONString(user));
        Result<User> userResult = userService.register(user);
        request.setAttribute(Contants.MESSAGE, userResult.getMessage());
        request.setAttribute(Contants.OBJECT, user);
        return "registerNew";
    }

    @RequestMapping("forgetPassword.html")
    public String toForgetPassword() {
        return "passwordNew";
    }

    @RequestMapping("forgetPassword")
    public String forgetPassword(User user) {
        logger.info("user:{}", JSON.toJSONString(user));
        Result<User> userResult = userService.forgetPassword(user);
        request.setAttribute(Contants.MESSAGE, userResult.getMessage());
        request.setAttribute(Contants.OBJECT, user);
        return "passwordNew";
    }


    private void cacheHelp() {
        Result<List<Game>> result = gameService.selectByExample(null);
        //初始化 游戏未接受计数器
        for (Game game : result.getData()) {
            Contants.GAME_COUNT_MAP.put(game.getId(), 0);
        }
        //初始化 订单类型计数器
        for (OrderTypeEnum type : OrderTypeEnum.values()) {
            Contants.ORDER_COUNT_MAP.put(type.getValue(), 0);
        }
        OrderExample example = new OrderExample();
        example.getOredCriteria().add(example.createCriteria().andTypeEqualTo(OrderTypeEnum.WAITING.getCode()));
        orderService.countByExample(example);
        Contants.GAME_RESULT.getData().clear();
        gameService.selectByExample(null);
    }
}
